<?php

namespace app\admin\controller;
use app\common\controller\Backend;
use app\admin\model\Admin;
use app\common\model\Category as CategoryModel;
use fast\Tree;
use app\common\model\Category;
use app\common\model\Articles;
/**
 * 微信用户管理
 *
 * @icon   fa fa-list
 * @remark 用于管理网站的所有分类,分类可进行无限级分类,分类类型请在常规管理->系统配置->字典配置中添加
 */
class Article extends Backend
{
	protected $noNeedLogin = [''];
    protected $noNeedRight = [''];

    public function _initialize()
    {
        parent::_initialize();
        //移除HTML标签
        $this->model = model('app\common\model\Articles');
    }
    public function index(){
    	if ($this->request->isAjax()) {
    		$map=[];
    		$map['wechat_id'] = $this->wechat_id;
    		list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
    		$list = $this->model->with('category')
                ->where($where)
                ->where($map)
                ->order($sort, $order)
                ->paginate($limit);
			$result = array("total" => $list->total(), "rows" => $list->items());
			return json($result);
    	}
    	return $this->view->fetch();
    }
    public function add(){
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $data['wechat_id'] = $this->wechat_id;
            $data['create_at'] = time();
            $result = $this->model->insert($data);
            if($result){
                $this->success('数据保存成功');
            }
            $this->error('数据保存失败');
        }
        $this->getCategorys();
        return $this->view->fetch();
    }
    public function edit($ids=null){
        $row = Articles::get($ids);
        if(empty($row)){
            $this->error('文章不存在.');
        }
        if($this->request->isPost()){
            $data = $this->request->post('row/a');
            $map['wechat_id'] = $this->wechat_id;
            $map['id'] = $ids;
            $data['update_at'] = time();
            $result = $this->model->where($map)->update($data);
            if($result){
                $this->success('数据保存成功');
            }
            $this->error('数据保存失败');
        }
        $this->getCategorys();
        $this->assign('row',$row);
        return $this->view->fetch();
    }
    public function getCategorys(){
        $tree = Tree::instance();
        $tree->init(collection(CategoryModel::order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        //$categorydata = [0 => ['type' => 'all', 'name' => __('请选择')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }
        $this->view->assign("parentList", $categorydata);
    }
}